const db = uniCloud.database()
const dbCmd = db.command

module.exports = {
  // 题目列表
  async examList() {
    let {
      from_lib,
      unit,
      exam_id,
      exam_type,
      exam_title,
      exam_name,
      pagesize = 20,
      pagenum = 1,
    } = this.params

    // 转换为Number类型
    pagesize = +pagesize
    pagenum = +pagenum

    // 页码不可小于1
    if (pagenum < 1) {
      throw handler.result({
        code: 40001,
        message: 'pagenum不可小于1'
      })
    }

    let examRes, pages, total

    const dbJQL = uniCloud.databaseForJQL({
      clientInfo: this.getClientInfo()
    })

    // 连接表实例
    let query = dbJQL.collection('sv-exam-list')

    // 全量查询
    if (pagesize < 1) {
      examRes = await query.get({
        getCount: true
      })
      // 总数统计
      total = examRes.count
      // 页数统计
      pages = Math.ceil(total / pagesize)

      throw handler.result({
        data: examRes.data,
        total,
        pagesize,
        pagenum,
        pages,
        params: this.params
      })
    }

    // 构建筛选条件(对象形式)
    const conditions = {}
    if (from_lib) {
      conditions.from_lib = dbCmd.eq(from_lib)
    }
    if (unit) {
      conditions.unit = dbCmd.eq(unit)
    }
    if (exam_id) {
      conditions.exam_id = dbCmd.eq(exam_id)
    }
    if (exam_type || exam_type === 0) {
      conditions.exam_type = dbCmd.eq(exam_type)
    }
    if (exam_title) {
      conditions.exam_title = new RegExp(exam_title.split('').join('.*'), 'i'); // 模糊查询
    }
    if (exam_name) {
      conditions.exam_name = new RegExp(exam_name.split('').join('.*'), 'i'); // 模糊查询
    }
    // 将所有有效的筛选条件添加到查询对象中
    if (Object.keys(conditions).length > 0) {
      query = query.where(conditions)
    }

    examRes = await query.orderBy('exam_index', 'asc')
      .skip(pagesize * (pagenum - 1)).limit(pagesize).get({
        getCount: true
      })

    total = examRes.count
    pages = Math.ceil(total / pagesize)

    return {
      data: examRes.data,
      total,
      pagesize,
      pagenum,
      pages,
      params: this.params
    }
  }
}